import fetch from 'node-fetch'
import FormData from 'form-data'
import fs from 'fs'
import path from 'path'

// TRF API 配置
const TRF_API_CONFIG = {
  API_URL: 'https://demo.ainsightflow.com/ainsightflow/public-api',
  API_KEY: 'ak_a21d1c5cc8ae496e98615a7dd525036d',
  SKILL_CODE: 'sgs_trf_v2_2'
}

/**
 * 获取请求头
 */
function getHeaders() {
  return {
    'Authorization': `Bearer ${TRF_API_CONFIG.API_KEY}`
  }
}

/**
 * 将CSV内容转换为TRF字段格式
 * @param {string} csvContent - CSV文件内容
 * @param {string} orderNo - 订单号
 * @returns {Array} TRF字段数组
 */
function csvToTrfFields(csvContent, orderNo) {
  const lines = csvContent.split('\n').filter(line => line.trim())
  const headers = lines[0].split(',').map(h => h.trim().toLowerCase())
  
  const extractFields = []
  
  for (let i = 1; i < lines.length; i++) {
    const values = lines[i].split(',').map(v => v.trim().replace(/^"|"$/g, ''))
    
    if (values.length >= 4) {
      const fieldCode = values[2]
      const displayName = values[3]
      // 支持FieldCode为空但为特定DisplayName的场景：用DisplayName作为field_code传给TRF
      const specialDisplayNames = new Set([
        'Name and Address of the Customer报告抬头',
        'Name of the Customer报告抬头',
        'Address of the Customer报告抬头',
        'report header is different from applicant Company Name',
        'report header is different from applicant Address'
      ])
      if (fieldCode || (displayName && specialDisplayNames.has(displayName))) {
        const effectiveCode = fieldCode || displayName
        const fieldObj = {
          order_no: orderNo,
          field_code: effectiveCode,
          field_type: 'input',
          field_display_name: displayName || effectiveCode
        }
        extractFields.push(fieldObj)
      }
    }
  }
  
  return extractFields
}

/**
 * 上传文档并处理（使用CSV字段定义）
 * @param {string} docFilePath - 文档文件路径
 * @param {string} csvContent - CSV内容
 * @param {string} orderNo - 订单号
 * @returns {Promise<Object>} API响应结果
 */
export async function uploadAndProcessWithCsv(docFilePath, csvContent, orderNo) {
  try {
    const url = `${TRF_API_CONFIG.API_URL}/document_process/upload_and_process`
    
    // 将CSV内容转换为TRF字段格式
    const trfExtractFields = csvToTrfFields(csvContent, orderNo)
    
    if (trfExtractFields.length === 0) {
      throw new Error('CSV文件中没有找到有效的字段定义')
    }
    
    console.log(`已加载 ${trfExtractFields.length} 个自定义字段`)
    
    // 创建FormData
    const formData = new FormData()
    
    // 添加文件
    const fileStream = fs.createReadStream(docFilePath)
    formData.append('files[]', fileStream, path.basename(docFilePath))
    
    // 添加其他参数
    formData.append('skill_code', TRF_API_CONFIG.SKILL_CODE)
    formData.append('trf_extract_fields', JSON.stringify(trfExtractFields))
    
    // 发送请求
    const response = await fetch(url, {
      method: 'POST',
      headers: getHeaders(),
      body: formData
    })
    
    if (!response.ok) {
      throw new Error(`HTTP错误: ${response.status} ${response.statusText}`)
    }
    
    const result = await response.json()
    
    if (!result.success) {
      throw new Error(result.message || '文档处理失败')
    }
    
    return result
    
  } catch (error) {
    console.error('TRF API调用错误:', error)
    throw error
  }
}

/**
 * 查询处理状态
 * @param {string} transactionId - 事务ID
 * @returns {Promise<Object>} 状态查询结果
 */
export async function getProcessStatus(transactionId) {
  try {
    const url = `${TRF_API_CONFIG.API_URL}/document_process/status/${transactionId}`
    
    const response = await fetch(url, {
      method: 'GET',
      headers: getHeaders()
    })
    
    if (!response.ok) {
      throw new Error(`HTTP错误: ${response.status} ${response.statusText}`)
    }
    
    const result = await response.json()
    
    if (!result.success) {
      throw new Error(result.message || '状态查询失败')
    }
    
    return result
    
  } catch (error) {
    console.error('状态查询错误:', error)
    throw error
  }
}

/**
 * 获取处理结果数据
 * @param {string} transactionId - 事务ID
 * @returns {Promise<Object>} 处理结果数据
 */
export async function getProcessResult(transactionId) {
  try {
    const url = `${TRF_API_CONFIG.API_URL}/document_process/result/${transactionId}`
    
    const response = await fetch(url, {
      method: 'GET',
      headers: getHeaders()
    })
    
    if (!response.ok) {
      throw new Error(`HTTP错误: ${response.status} ${response.statusText}`)
    }
    
    const result = await response.json()
    return result
    
  } catch (error) {
    console.error('获取处理结果错误:', error)
    throw error
  }
}

/**
 * 等待处理完成
 * @param {string} transactionId - 事务ID
 * @param {number} timeout - 超时时间（秒），默认3600秒
 * @param {number} pollInterval - 轮询间隔（秒），默认15秒
 * @returns {Promise<Object>} 最终处理结果
 */
export async function waitForCompletion(transactionId, timeout = 3600, pollInterval = 15) {
  const startTime = Date.now()
  const timeoutMs = timeout * 1000
  const pollIntervalMs = pollInterval * 1000
  
  while (Date.now() - startTime < timeoutMs) {
    try {
      const result = await getProcessStatus(transactionId)
      
      const transactionStatus = result.status
      console.log(`事务状态: ${transactionStatus}`)
      
      // 检查所有文件的状态
      const files = result.files || []
      if (files.length > 0) {
        let allFilesFinished = true
        
        for (const file of files) {
          const fileStatus = file.status
          console.log(`  文件 ${file.file_name}: ${fileStatus}`)
          
          // 只有completed或error才算完成
          if (fileStatus !== 'completed' && fileStatus !== 'error') {
            allFilesFinished = false
          }
        }
        
        // 所有文件都已完成
        if (allFilesFinished) {
          console.log('所有文件处理完成，返回完整结果...')
          console.log('处理结果数据:', JSON.stringify(result, null, 2))
          return result
        }
      }
      
      // 如果transaction状态为error，直接返回错误
      if (transactionStatus === 'error') {
        throw new Error(`处理失败: ${JSON.stringify(result)}`)
      }
      
      // 等待下次轮询
      await new Promise(resolve => setTimeout(resolve, pollIntervalMs))
      
    } catch (error) {
      console.error('轮询过程中出错:', error)
      throw error
    }
  }
  
  throw new Error('处理超时')
}

/**
 * 完整的文档处理流程
 * @param {string} docFilePath - 文档文件路径
 * @param {string} csvContent - CSV内容
 * @param {string} orderNo - 订单号
 * @returns {Promise<Object>} 完整的处理结果
 */
/**
 * 检查是否已存在TRF API结果缓存文件
 * @param {string} orderNo - 订单号
 * @returns {Object|null} 如果存在缓存则返回结果，否则返回null
 */
export async function checkTrfResultCache(orderNo) {
  try {
    const cacheDir = path.join(process.cwd(), 'trf-results')
    const cacheFilePath = path.join(cacheDir, `${orderNo}.json`)
    
    if (fs.existsSync(cacheFilePath)) {
      console.log(`找到TRF结果缓存文件: ${orderNo}.json`)
      const cachedResult = JSON.parse(fs.readFileSync(cacheFilePath, 'utf8'))
      return cachedResult
    }
    
    return null
  } catch (error) {
    console.error('检查TRF结果缓存时出错:', error)
    return null
  }
}

/**
 * 保存TRF API结果到缓存文件
 * @param {string} orderNo - 订单号
 * @param {Object} result - TRF API处理结果
 */
export async function saveTrfResultCache(orderNo, result) {
  try {
    const cacheDir = path.join(process.cwd(), 'trf-results')
    
    // 确保缓存目录存在
    if (!fs.existsSync(cacheDir)) {
      fs.mkdirSync(cacheDir, { recursive: true })
    }
    
    const cacheFilePath = path.join(cacheDir, `${orderNo}.json`)
    
    // 添加缓存时间戳
    const cacheData = {
      ...result,
      cached_at: new Date().toISOString(),
      order_no: orderNo
    }
    
    fs.writeFileSync(cacheFilePath, JSON.stringify(cacheData, null, 2), 'utf8')
    console.log(`TRF结果已保存到缓存文件: ${orderNo}.json`)
    
  } catch (error) {
    console.error('保存TRF结果缓存时出错:', error)
  }
}

/**
 * 获取TRF缓存文件列表和统计信息
 */
export async function getTrfCacheStats() {
  try {
    const cacheDir = path.join(process.cwd(), 'trf-results')
    
    if (!fs.existsSync(cacheDir)) {
      return {
        totalFiles: 0,
        totalSize: 0,
        files: []
      }
    }
    
    const files = fs.readdirSync(cacheDir).filter(file => file.endsWith('.json'))
    let totalSize = 0
    const fileStats = []
    
    for (const file of files) {
      const filePath = path.join(cacheDir, file)
      const stats = fs.statSync(filePath)
      const fileData = JSON.parse(fs.readFileSync(filePath, 'utf8'))
      
      totalSize += stats.size
      fileStats.push({
        filename: file,
        orderNo: fileData.order_no || file.replace('.json', ''),
        size: stats.size,
        createdAt: stats.birthtime,
        modifiedAt: stats.mtime,
        cachedAt: fileData.cached_at || stats.birthtime.toISOString(),
        age: Date.now() - new Date(fileData.cached_at || stats.birthtime).getTime()
      })
    }
    
    // 按创建时间排序（最新的在前）
    fileStats.sort((a, b) => new Date(b.cachedAt) - new Date(a.cachedAt))
    
    return {
      totalFiles: files.length,
      totalSize,
      files: fileStats
    }
  } catch (error) {
    console.error('获取TRF缓存统计信息时出错:', error)
    throw error
  }
}

/**
 * 清理TRF缓存文件
 * @param {Object} options - 清理选项
 * @param {number} options.maxAge - 最大保留时间（毫秒）
 * @param {number} options.maxFiles - 最大保留文件数
 * @param {Array<string>} options.specificFiles - 指定要删除的文件名列表
 */
export async function cleanTrfCache(options = {}) {
  try {
    const cacheDir = path.join(process.cwd(), 'trf-results')
    
    if (!fs.existsSync(cacheDir)) {
      return {
        success: true,
        deletedFiles: [],
        message: '缓存目录不存在'
      }
    }
    
    const stats = await getTrfCacheStats()
    let filesToDelete = []
    
    // 如果指定了特定文件，只删除这些文件
    if (options.specificFiles && options.specificFiles.length > 0) {
      filesToDelete = stats.files.filter(file => 
        options.specificFiles.includes(file.filename) || 
        options.specificFiles.includes(file.orderNo)
      )
    } else {
      // 基于时间清理
      if (options.maxAge) {
        const oldFiles = stats.files.filter(file => file.age > options.maxAge)
        filesToDelete = filesToDelete.concat(oldFiles)
      }
      
      // 基于文件数量清理（保留最新的文件）
      if (options.maxFiles && stats.files.length > options.maxFiles) {
        const excessFiles = stats.files.slice(options.maxFiles)
        filesToDelete = filesToDelete.concat(excessFiles)
      }
    }
    
    // 去重
    filesToDelete = filesToDelete.filter((file, index, self) => 
      index === self.findIndex(f => f.filename === file.filename)
    )
    
    const deletedFiles = []
    
    for (const file of filesToDelete) {
      const filePath = path.join(cacheDir, file.filename)
      try {
        fs.unlinkSync(filePath)
        deletedFiles.push({
          filename: file.filename,
          orderNo: file.orderNo,
          size: file.size,
          cachedAt: file.cachedAt
        })
        console.log(`已删除TRF缓存文件: ${file.filename}`)
      } catch (deleteError) {
        console.error(`删除文件 ${file.filename} 时出错:`, deleteError)
      }
    }
    
    return {
      success: true,
      deletedFiles,
      message: `成功清理 ${deletedFiles.length} 个缓存文件`
    }
    
  } catch (error) {
    console.error('清理TRF缓存时出错:', error)
    throw error
  }
}

/**
 * 清理所有TRF缓存文件
 */
export async function clearAllTrfCache() {
  try {
    const cacheDir = path.join(process.cwd(), 'trf-results')
    
    if (!fs.existsSync(cacheDir)) {
      return {
        success: true,
        deletedFiles: [],
        message: '缓存目录不存在'
      }
    }
    
    const files = fs.readdirSync(cacheDir).filter(file => file.endsWith('.json'))
    const deletedFiles = []
    
    for (const file of files) {
      const filePath = path.join(cacheDir, file)
      try {
        const stats = fs.statSync(filePath)
        fs.unlinkSync(filePath)
        deletedFiles.push({
          filename: file,
          size: stats.size
        })
        console.log(`已删除TRF缓存文件: ${file}`)
      } catch (deleteError) {
        console.error(`删除文件 ${file} 时出错:`, deleteError)
      }
    }
    
    return {
      success: true,
      deletedFiles,
      message: `成功清理所有 ${deletedFiles.length} 个缓存文件`
    }
    
  } catch (error) {
    console.error('清理所有TRF缓存时出错:', error)
    throw error
  }
}

export async function processDocumentComplete(docFilePath, csvContent, orderNo) {
  try {
    console.log('开始上传和处理文档...')
    
    // 1. 上传并开始处理
    const uploadResult = await uploadAndProcessWithCsv(docFilePath, csvContent, orderNo)
    const transactionId = uploadResult.transaction_id
    
    console.log(`事务ID: ${transactionId}`)
    
    // 2. 等待处理完成
    console.log('等待处理完成...')
    const finalResult = await waitForCompletion(transactionId)
    
    console.log('文档处理完成')
    
    // 3. 解析CSV，提取DFF字段代码并保存到缓存
    const csvMeta = extractDffFieldCodesFromCsv(csvContent)
    const finalResultWithCsvMeta = {
      ...finalResult,
      csv_meta: csvMeta
    }
    await saveTrfResultCache(orderNo, finalResultWithCsvMeta)
    
    return finalResult
    
  } catch (error) {
    console.error('文档处理流程错误:', error)
    throw error
  }
}

/**
 * 从CSV内容中提取 type 为 DFF 的字段代码
 * @param {string} csvContent
 * @returns {{ dff_fieldcodes: string[], total_rows: number }}
 */
function extractDffFieldCodesFromCsv(csvContent) {
  try {
    if (!csvContent || typeof csvContent !== 'string') {
      return { dff_fieldcodes: [], total_rows: 0 }
    }
    const lines = csvContent.split(/\r?\n/).filter(l => l.trim().length > 0)
    if (lines.length <= 1) {
      return { dff_fieldcodes: [], total_rows: lines.length }
    }
    // 预期头: order_no,type,FieldCode,DisplayName
    const header = lines[0]
    const cols = header.split(',')
    const typeIdx = cols.findIndex(c => c.trim().toLowerCase() === 'type')
    const codeIdx = cols.findIndex(c => c.trim().toLowerCase() === 'fieldcode')
    const dffCodes = new Set()
    for (let i = 1; i < lines.length; i++) {
      const row = lines[i]
      // 简易CSV拆分（当前内容字段较为简单，无需完整解析器）
      const parts = row.split(',')
      if (parts.length < Math.max(typeIdx, codeIdx) + 1) continue
      const typeVal = (parts[typeIdx] || '').trim().toLowerCase()
      const codeVal = (parts[codeIdx] || '').trim()
      if (!codeVal) continue
      if (typeVal === 'dff') {
        dffCodes.add(codeVal)
      }
    }
    const dff_fieldcodes = Array.from(dffCodes)
    // console.log(`CSV解析: 识别到 ${dff_fieldcodes.length} 个DFF字段代码`)
    // console.log('CSV DFF字段代码列表:', dff_fieldcodes)
    return { dff_fieldcodes, total_rows: lines.length - 1 }
  } catch (e) {
    console.warn('从CSV提取DFF字段代码时出错:', e)
    return { dff_fieldcodes: [], total_rows: 0 }
  }
}

export function buildTrfRequestPreview(csvContent, orderNo) {
  const fields = csvToTrfFields(csvContent, orderNo)
  return {
    skill_code: TRF_API_CONFIG.SKILL_CODE,
    trf_extract_fields: fields
  }
}